(function() {
    var myApp = angular.module('myApp');

    myApp.run(function($rootScope, mtAjax) {

        $rootScope.ztree = {
            init: function($event) {
                $rootScope.ztree.obj = $event[0];
            },
            obj: null,
            sel: []
        };

        $rootScope.treeSelect = [];

    });

    //角色列表
    myApp.controller("myRoleTableController", function($scope, $rootScope, $log, myRoleTableOption,myUserTableOption, reqDataByAjax, $compile, mtShowModal,mtRefreshTable ) {
        $scope.option = myRoleTableOption;
        $scope.option1=myUserTableOption;
        //重点模块，必有，如果没有，拼接的按钮无法生效
        $scope.option.rowCallback = function(row, data, index) {
            $compile(angular.element(row))($scope);
        };
        $scope.option.ajax = ajax;
        $scope.option1.ajax = ajax1;
        function ajax(data, callback, settings) {
            data.length=10;
            reqDataByAjax("/scheduling/api/user/role/getallrole", data).then(function (ret) {
                $scope.roleList=ret[0];
                callback({
                    "draw": data.draw,
                    "recordsTotal": ret[1][0].recordsTotal,
                    "recordsFiltered": ret[2][0].recordsFiltered,
                    "data": ret[0]
                });
            });
        }
        function ajax1(data, callback, settings) {
            data.role_id=$rootScope.roleId;
            reqDataByAjax("/scheduling/api/user/role/getalluser", data).then(function (ret) {
                $scope.userlist=ret[0];
                callback({
                    "draw": data.draw,
                    "recordsTotal": ret[1][0].recordsTotal,
                    "recordsFiltered": ret[2][0].recordsFiltered,
                    "data": ret[0]
                });
                $('#selectall').prop('checked',false);
                $('#usertable tbody tr ').removeClass('selected');
                $scope.if_all=true;
                for(var i=0;i<$scope.userlist.length;i++){
                    if($scope.userlist[i].selected==1){
                        $('#usertable tbody tr').eq(i).addClass('selected');
                    }else{
                        $scope.if_all=false;
                    }
                }
                if($scope.if_all){
                    $('#selectall').prop('checked',true);
                }

            });
        }
        $('#usertable tbody').on('click', 'tr', function () {
            console.log(($('#usertable tbody tr').eq($(this).index()).hasClass("selected")));
            if(!$('#usertable tbody tr').eq($(this).index()).hasClass("selected")){
                $('#usertable tbody tr ').eq($(this).index()).addClass('selected');
                $('#usertable tbody tr input').eq($(this).index()).prop('checked',true);
                for(var i=0;i<$('#usertable tbody tr input').length;i++){
                    if($('#usertable tbody tr input').eq(i).prop('checked')){
                        continue;
                    }else{
                        $('#selectall').prop('checked',false);
                        return;
                    }
                }
                $('#selectall').prop('checked',true);
            }else{
                $('#usertable tbody tr ').eq($(this).index()).removeClass('selected');
                $('#usertable tbody tr input').eq($(this).index()).prop('checked',false);
                for(var i=0;i<$('#usertable tbody tr input').length;i++){
                    if($('#usertable tbody tr input').eq(i).prop('checked')){
                        continue;
                    }else{
                        $('#selectall').prop('checked',false);
                        return;
                    }
                }
                $('#selectall').prop('checked',true);
            }
        } );
        $scope.selectAll=function(){
            if( $('#selectall').prop('checked')){
                for(var i=0;i<$('#usertable tbody tr input').length;i++){
                    $('#usertable tbody tr input').eq(i).prop('checked',true);
                    $('#usertable tbody tr').eq(i).addClass("selected");
                }
            }else{
                for(var i=0;i<$('#usertable tbody tr input').length;i++){
                    $('#usertable tbody tr input').eq(i).prop('checked',false);
                    $('#usertable tbody tr').eq(i).removeClass("selected");
                }
            }
        };

        //新建角色按钮弹出模态框
        $scope.showaddrole=function(){
            $scope.role = {
                status: 1
            };
            $('#addroleModal').modal('show');
        };
        // 创建角色保存
        $scope.roleSave = function(e) {
            reqDataByAjax("/scheduling/api/user/role/addrole", $scope.role, "POST")
                .then(function(data) {
                    $('#addroleModal').modal('hide');
                    mtRefreshTable('roletable');
                },function(){
                    alert('创建角色失败！');
                });
        };
        //编辑角色模态框
        $scope.showeditmodal=function(index){
            $scope.role=$scope.roleList[index];
            $('#editroleModal').modal('show');
        };

        //删除角色模态框
        $scope.deleterolemodal=function(index){
            $scope.role=$scope.roleList[index];
            $('#removerole').modal('show');
        };
        //删除角色保存
        $scope.removeRoleSave=function(){
            reqDataByAjax("/scheduling/api/user/role/deleterole", $scope.role,'POST').then(function (ret) {
                $('#removerole').modal('hide');
                $('#groupremoved').modal('show');
                mtRefreshTable('roletable');
            });
        };
        //编辑角色保存
        $scope.editroleSave=function(){
            reqDataByAjax("/scheduling/api/user/role/modifyrole", $scope.role,'POST').then(function (ret) {
                $('#editroleModal').modal('hide');
                alert('保存成功！');
                mtRefreshTable('roletable');
            });
        };
        // 设置角色菜单信息
        $scope.setMenus = function(roleid,roleName) {
            $rootScope.roleId = roleid;
            $rootScope.roleName = roleName;
            mtShowModal("#menuTreeModal");
        };
        // 设置角色用户信息
        $scope.setUsers = function(roleid,roleName) {
            $rootScope.roleId = roleid;
            $rootScope.roleName = roleName;
            mtShowModal("#roleUserModal");
            mtRefreshTable("#usertable");
        };
        //保存用户角色信息
        $scope.ok=function() {
            $scope.selectUser = [];
            for (var i = 0; i < $('#usertable tbody tr input').length; i++) {
                if ($('#usertable tbody tr input').eq(i).prop('checked')) {
                    var params = {
                        user_id: $scope.userlist[i].user_id,
                        role_id:$rootScope.roleId
                    };
                    $scope.selectUser.push(params);
                }
            }
            var param={
                role_id:$rootScope.roleId
            };
            reqDataByAjax('/scheduling/api/user/role/clearroleusers', param, 'POST').then(function (ret) {
                if($scope.selectUser.length>0){
                    reqDataByAjax('/scheduling/api/user/role/saveroleusers',$scope.selectUser, 'POST').then(function (ret) {
                        alert('保存成功！');
                    });
                }else{
                    alert('保存成功！')
                }

            });
        }
    });

    myApp.controller("menuTreeController", function($rootScope,$scope, $log, mtAjax) {

        // 显示初始化时
        $scope.modalShown = function($event) {

            // if($rootScope.selected.length > 0){
            //     $scope.roleName = $rootScope.selected[0].name;
            // }
            $scope.roleName = $rootScope.roleName;

            var ztree = $rootScope.ztree.obj;
            ztree && ztree.reAsyncChildNodes(null, "refresh", false);

        };

        $scope.option = {
            async: {
                enable: true,
                url: '/scheduling/api/user/role/menuselect',
                contentType: 'application/json',
                type: 'get',
                dataType: 'json',
                autoParam: ['group_id'],
                dataFilter: dataFilter
            },
            check: {
                enable: true
            },
            callback: {
                beforeAsync: beforeAsync,
                onNodeCreated: onNodeCreated,
                onClick: onClick
            },
            data: {
                key: {
                    url: '_url_'
                }
            }
        };

        function dataFilter(treeId, parentNode, data) {
            var treeNodes = [];
            var groups = data.data[0],
                items = data.data[1];
            for(var i = 0; i < groups.length; ++i) {
                var item = $.extend({
                    isParent: true
                }, groups[i]);
                treeNodes.push(item);
            }

            for(var i = 0; i < items.length; ++i) {
                var item = $.extend({
                    isParent: false
                }, items[i]);
                // 默认选中
                for(var j = 0; j < $rootScope.treeSelect.length; j++) {
                    if($rootScope.treeSelect[j].group_id == items[i].group_id) {
                        item.checked = 1;
                        break;
                    }

                }
                treeNodes.push(item);
            }
            return treeNodes;
        }

        function beforeAsync(treeId, treeNode) {
            var ztree = $rootScope.ztree.obj;
            if(!ztree)
                return true;

            // var role_id = null;
            // var roleSel = $rootScope.roleTable.sel;
            // if(roleSel && roleSel.length)
            //  role_id = roleSel[0].role_id;

            // var system_id = $rootScope.system.sel;
            // if($rootScope.selected.length > 0){
            //     ztree.setting.async.otherParam = {
            //         role_id: $rootScope.selected[0].role_id
            //     };
            // }

            if($rootScope.roleId ){
                ztree.setting.async.otherParam = {role_id: $rootScope.roleId};
            }


            return true;
        }

        function onNodeCreated(event, treeId, treeNode) {
            var ztree = $rootScope.ztree.obj;
            if(!ztree)
                return;

            ztree.expandNode(treeNode, true);
        }

        function onClick(event, treeId, treeNode, clickFlag) {
            var ztree = $rootScope.ztree.obj;
            if(!ztree)
                return;

            ztree.checkNode(treeNode, undefined, true, true);
        }

        // 保存选择
        $scope.ok = function() {
            // var role_id = $rootScope.roleTable.sel[0].role_id;
            $rootScope.treeSelect = $rootScope.ztree.sel;

            for(var i=0;i<$rootScope.ztree.sel.length;i++){
                // $rootScope.treeSelect[i] = angular.extend($rootScope.treeSelect[i], { role_id: $scope.$root.selected[0].role_id })
                $rootScope.treeSelect[i] = angular.extend($rootScope.treeSelect[i], { role_id: $rootScope.roleId})

            }

            // if($rootScope.treeSelect.length > 0)
            //     $rootScope.selectUsers = "已选择";

            //
            mtAjax("/scheduling/api/user/role/saveRoleMenus", $rootScope.treeSelect, 'POST').then(function (ret) {
                alert('保存成功！');
                $rootScope.treeSelect=[];
                // mtRefreshTable("#tablelist");
            },function (ret) {
                alert('保存失败！');
            });

        };

        $scope.cancel = function() {
            $rootScope.treeSelect = [];

        };

    });


    //设置角色权限
    myApp.controller("myRolePermissionController", function($scope, $log
        , myPermissionTableOption,  reqDataByAjax,$compile,mtAjax,mtRefreshTable
    ) {
        // 切换至用户表页面时，刷新用户表
        $scope.$on("shown.bs.tab", function(event, element, target) {
            if (target.is("#permission"))
                $scope.$root.$broadcast("refresh.table", "#permissiontable1");
        });

        // 设置用户表Option
        $scope.option = myPermissionTableOption;

        // 操作栏
        var caozuo = {
            render: function(data, type, row, meta) {

                var strBtn = "";

                strBtn += '<button class="btn btn-primary btn-xs" ng-click="deleteper(\'' + row.site_id + '\',\'' + row.name + '\',\'' + row.permission_id + '\')" >移除权限</button>';
                return strBtn;
            }
        };

        $scope.option["columns"].push(caozuo);
        $scope.option.rowCallback = function(row, data, index) {
            $compile(angular.element(row))($scope);
        };

        $scope.option.ajax = ajax;
        function ajax(data, callback, settings) {
            data.role_id = $scope.$root.selectedRoles && $scope.$root.selectedRoles.length && $scope.$root.selectedRoles[0].role_id;
            reqDataByAjax("/scheduling/api/user/role/getallpermission", data).then(function (ret) {
                callback({
                    "draw": data.draw,
                    "recordsTotal": ret[1][0].recordsTotal,
                    "recordsFiltered": ret[2][0].recordsFiltered,
                    "data": ret[0]
                });
            });
        }


         // 删除角色权限设置
        
         $scope.deleteper = function(site_id,name,permission_id) {
           
            var confirmRslt = confirm("从角色权限 中移除此权限: " + name +" ?");

            if(confirmRslt){
                var role_id = $scope.$root.selectedRoles[0].role_id;
                var deleteParams = {
                    role_id: role_id,
                    site_id: site_id,
                    permission_id:permission_id
                };

                // 删除用户
        
                mtAjax("/scheduling/api/user/role/deletepermission",deleteParams,"POST").then(function(ret){

                    alert('删除成功！');
                    mtRefreshTable("#permissiontable1");
                },function(ret){
                    alert('删除失败！');
                });
            }

        };

        // 设置用户表默认选中
        // $scope.$on("draw.dt", function(event, element, e, settings) {
        //     if (!element.is('#permissiontable'))
        //         return;

        //     var table = $.fn.dataTable.tables({ visible: false, api: true }).table(element);
        //     if (!table.node())
        //         return;

        //     var si = [];
        //     table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
        //         var d = this.data();
        //         d.selected && si.push(rowIdx);
        //     });

        //     table.rows(si).select();
        // });

        // 记录当前选中权限
        // $scope.permissions = [];
        // $scope.$on("select", function (event, element, e, dt, type, indexes) {
        //     if (element.is("#permissiontable"))
        //         $scope.permissions = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        // });

        // $scope.$on("deselect", function (event, element, e, dt, type, indexes) {
        //     if (element.is("#permissiontable"))
        //         $scope.permissions = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        // });

        // $scope.$on("draw.dt", function (event, element, e, settings) {
        //     if (element.is("#permissiontable"))
        //         $scope.permissions = [];
        // });

        // 保存角色权限设置
        // $scope.ok = function() {
        //     var role_id = $scope.$root.selectedRoles[0].role_id;
        //     var permissions   = $scope.permissions;
        //     var url;
        //     if (permissions.length == 0) {
        //         permissions.push({ role_id : role_id });
        //         url = "/scheduling/api/user/role/clearrolepermissions";
        //     } else {
        //         for (var p in permissions)
        //             permissions[p].role_id = role_id;
        //         url = "/scheduling/api/user/role/saverolepermissions";
        //     }
        //     reqDataByAjax(url, permissions, "POST");
        // };
    });


     // 添加选中权限
     myApp.controller("addqx", function($scope, $log
        , selectqxTableOption, reqDataByAjax,mtAjax, mtShowTab, mtRefreshTable
    ) {
        // 切换至permission页面时，刷新表permissiontable1
        $scope.$on("shown.bs.tab", function(event, element, target) {
            if (target.is("#permission"))
                $scope.$root.$broadcast("refresh.table", "#permissiontable1");
        });

        // 权限Option
        $scope.option = selectqxTableOption;
        $scope.option.ajax = ajax;
        function ajax(data, callback, settings) {
            data.role_id = $scope.$root.selectedRoles && $scope.$root.selectedRoles.length && $scope.$root.selectedRoles[0].role_id;
            reqDataByAjax("/scheduling/api/user/role/getallqx", data).then(function (ret) {
                if(ret.params['search[value]'] == ""){
                    $scope.users = [];
                }
                callback({
                    "draw": data.draw,
                    "recordsTotal": ret[1][0].recordsTotal,
                    "recordsFiltered": ret[2][0].recordsFiltered,
                    "data": ret[0]
                });
            });
        }


        // 记录当前选中用户
        $scope.qx = [];
        $scope.$on("select", function(event, element, e, dt, type, indexes) {
            if (element.is("#permissiontable"))
                $scope.qx = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        });
        $scope.$on("deselect", function(event, element, e, dt, type, indexes) {
            if (element.is("#permissiontable"))
                $scope.qx = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        });
        $scope.$on("draw.dt", function(event, element, e, settings) {
            if (element.is("#permissiontable"))
                $scope.qx = [];
        });

        // 保存用户
        $scope.ok = function() {
            var role_id = $scope.$root.selectedRoles[0].role_id;
            var qx   = $scope.qx;
            var saveqx = [];
            for(var i=0;i<qx.length;i++){
                saveqx[i]=angular.extend(qx[i], {role_id:role_id});
            }
            var url;
            
            // 添加用户
            mtAjax("/scheduling/api/user/role/saverolepermissions",saveqx,"POST").then(function(ret){

                alert('添加权限成功！');
                mtShowTab("#roleuserlist");
                mtRefreshTable("#permissiontable");
                
                mtShowTab("#permission");
                mtRefreshTable("#permissiontable1");
                // mtShowTab("#permissionlist");
            },function(ret){
                alert('添加权限失败！');
            });
        };
    });

    

    // 角色用户列表
    myApp.controller("myRoleUserListController", function($scope, $log, myRoleUserListTableOption, reqDataByAjax,mtAjax, $compile,mtRefreshTable
    ) {
        // 切换至用户表页面时，刷新用户表
        $scope.$on("shown.bs.tab", function(event, element, target) {
            if (target.is("#roleuserlist"))
                $scope.$root.$broadcast("refresh.table", "#roleuserlisttable");
        });

        // 设置用户表Option
        $scope.option = myRoleUserListTableOption;

        // 操作栏
        var caozuoButton = {
            render: function(data, type, row, meta) {

                var strBtn = "";

                strBtn += '<button class="btn btn-primary btn-xs" ng-click="deleteUser(\'' + row.user_id + '\',\'' + row.cname + '\')" >移除用户</button>';
                return strBtn;
            }
        };

        $scope.option["columns"].push(caozuoButton);
        $scope.option.rowCallback = function(row, data, index) {
            $compile(angular.element(row))($scope);
        };

        $scope.option.ajax = ajax;
        function ajax(data, callback, settings) {
            data.role_id = $scope.$root.selectedRoles && $scope.$root.selectedRoles.length && $scope.$root.selectedRoles[0].role_id;
            reqDataByAjax("/scheduling/api/user/role/getalluser", data).then(function (ret) {
                if(ret.params['search[value]'] == ""){
                    $scope.users = [];
                }
                callback({
                    "draw": data.draw,
                    "recordsTotal": ret[1][0].recordsTotal,
                    "recordsFiltered": ret[2][0].recordsFiltered,
                    "data": ret[0]
                });
            });
        }

        $scope.$on("draw.dt", function (event, element, e, settings) {
            // if (element.is("#usertable"))
            //     $scope.users = [];
        });

        // 删除角色用户设置
        $scope.deleteUser = function(user_id, user_name) {
            var confirmRslt = confirm("从角色："+$scope.$root.selectedRoles[0].descr+" 中移除此用户: " + user_name +" ?");

            if(confirmRslt){
                var role_id = $scope.$root.selectedRoles[0].role_id;
                var users   = $scope.users;
                var deleteParams = {
                    role_id: role_id,
                    user_id: user_id
                };

                // 删除用户
                mtAjax("/scheduling/api/user/role/deleteroleuser",deleteParams,"POST").then(function(ret){

                    alert('删除成功！');
                    mtRefreshTable("#roleuserlisttable");
                },function(ret){
                    alert('删除失败！');
                });
            }

        };
    });

    // 添加选中用户
    myApp.controller("addUserController", function($scope, $log
        , selectUserTableOption, reqDataByAjax,mtAjax, mtShowTab, mtRefreshTable) {
        // 切换至用户表页面时，刷新用户表
        $scope.$on("shown.bs.tab", function(event, element, target) {
            if (target.is("#adduser"))
                $scope.$root.$broadcast("refresh.table", "#selectusertable");
        });

        // 用户Option
        $scope.option = selectUserTableOption;
        $scope.option.ajax = ajax;
        function ajax(data, callback, settings) {
            data.role_id = $scope.$root.selectedRoles && $scope.$root.selectedRoles.length && $scope.$root.selectedRoles[0].role_id;
            reqDataByAjax("/scheduling/api/user/role/getallnoselectuser", data).then(function (ret) {
                if(ret.params['search[value]'] == ""){
                    $scope.users = [];
                }
                callback({
                    "draw": data.draw,
                    "recordsTotal": ret[1][0].recordsTotal,
                    "recordsFiltered": ret[2][0].recordsFiltered,
                    "data": ret[0]
                });
            });
        }


        // 记录当前选中用户
        $scope.users = [];
        $scope.$on("select", function(event, element, e, dt, type, indexes) {
            if (element.is("#selectusertable"))
                $scope.users = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        });
        $scope.$on("deselect", function(event, element, e, dt, type, indexes) {
            if (element.is("#selectusertable"))
                $scope.users = Array.prototype.slice.call(dt.rows('.selected').data(), 0);
        });
        $scope.$on("draw.dt", function(event, element, e, settings) {
            if (element.is("#selectusertable"))
                $scope.users = [];
        });

        // 保存用户
        $scope.addUser = function() {
            var role_id = $scope.$root.selectedRoles[0].role_id;
            var users   = $scope.users;
            var saveUsers = [];
            for(var i=0;i<users.length;i++){
                saveUsers[i]=angular.extend(users[i], {role_id:role_id});
            }
            var url;
            
            // 添加用户
            mtAjax("/scheduling/api/user/role/saveroleusers",saveUsers,"POST").then(function(ret){

                alert('添加用户成功！');
                mtRefreshTable("#selectusertable");
                mtRefreshTable("#roleuserlisttable");
                mtShowTab("#roleuserlist");
            },function(ret){
                alert('添加用户失败！');
            });
        };
    });



})();


